import 'package:dio/dio.dart';
import 'dart:convert';
import 'dart:core';
import 'package:flutter/foundation.dart';
import 'package:flutter_project/common/route_page/route_name.dart';
import 'package:flutter_project/config/common_string_config.dart';
import 'package:flutter_project/config/loading_toast.dart';
import 'package:flutter_project/user/user_login/user_login_view.dart';

class HttpDioUtils {
  HttpDioUtils(_);

  static String baseUrl =
      'https://internal.aispheretech.com/creative_platform/';

  static final BaseOptions _options = BaseOptions(
    baseUrl: baseUrl,
    connectTimeout: const Duration(seconds: 10),
    receiveTimeout: const Duration(seconds: 10),
    headers: {"content-type": "application/json"},
  );

  static final Dio _dio = Dio(_options);

  static Future requestPostUrl(
      {String apiUrl = '', Map<String, dynamic>? dataMap}) async {
    var requestObj;
    // 1.请求的单独配置
    final options = Options(method: 'post', headers: <String, dynamic>{
      "Token": CommonStringConfig.loginToken,
      "Ai-Trace-Id": 'f10cecf4-7225-4dec-b169-b255ef5f172c',
    });
    try {
      Response response =
          await _dio.post(apiUrl, queryParameters: dataMap, options: options);
      if (response.statusCode == 200 || response.data != null) {
        requestObj = response.data;
      }
      return requestObj;
    } on DioException catch (e) {
      debugPrint(e.response?.data);
      return requestObj;
    }
  }

  static Future requestGetUrl(
      {String apiUrl = '', Map<String, dynamic>? dataMap}) async {
    var requestObj;

    try {
      final options = Options(method: 'post', headers: <String, dynamic>{
        "Token": CommonStringConfig.loginToken,
        "Ai-Trace-Id": CommonStringConfig.uuid,
      });
      Response response =
          await _dio.get(apiUrl, queryParameters: dataMap, options: options);
      if (response.statusCode == 200 || response.data != null) {
        requestObj = response.data;
        if (kDebugMode) {
          print('$baseUrl$apiUrl');
          print('rx---------${response.data}');
        }
      }
    } on DioException catch (e) {
      debugPrint(e.response?.data);
      return requestObj;
    }

    return requestObj;
  }

  static Future? uploadFileUrl(String url,
      {String prefixPath = "",
      required Map<String, dynamic> params,
      ProgressCallback? sendCallback}) async {
    final options = Options(headers: <String, dynamic>{});
    try {
      Response res = await _dio.post<String>("$prefixPath/$url",
          data: FormData.fromMap(params),
          options: options,
          onSendProgress: sendCallback);
      if (res.data != null) {
        return res.data;
      }
      return null;
    } on DioException catch (e) {
      Future.error(e);
    }
    return null;
  }

  static Future? uploadMultipartFileUrl(String url,
      {String prefixPath = "",
      required Map<String, dynamic> params,
      ProgressCallback? sendCallback}) async {
    final options = Options(headers: <String, dynamic>{});
    FormData formData = FormData.fromMap({
      "file": await MultipartFile.fromFile("path/to/video.mp4",
          filename: "video.mp4"),
    });
    try {
      Response res = await _dio.post<String>("$prefixPath/$url",
          data: formData, options: options, onSendProgress: sendCallback);
      if (res.data != null) {
        return res.data;
      }
      return null;
    } on DioException catch (e) {
      Future.error(e);
    }
    return null;
  }

  static Future? request(String url,
      {String method = 'post',
      Map<String, dynamic>? params,
      Interceptor? inter,
      bool isShowToast = true}) async {
    final options = Options(method: 'post', headers: <String, dynamic>{
      "Token": CommonStringConfig.loginToken,
      "Ai-Trace-Id": CommonStringConfig.uuid,
    });
    try {
      Response response = await _dio.request<String>(url,
          data: method.toLowerCase() != 'get' ? params : null,
          queryParameters: method.toLowerCase() == 'get' ? params : null,
          options: options);
      if (response.statusCode == 200 || response.data != null) {
        final obj = jsonDecode(response.data);
        if (kDebugMode) {
          print('$baseUrl$url');
          print('rx---------${response.data}');
        }
        if (isShowToast) {
          if (obj != null && obj['ErrCode'] != 0) {
            String msg = obj['ErrMsg'];
            if (msg.isNotEmpty) {
              toast(msg);
              if(msg.contains('过期')){
                RouteNames.openAndRemovedUntilWidget(const UserLoginView());
                return;
              }
            }
          }
        }

        return obj;
      }
      return null;
    } on DioException catch (e) {
      debugPrint('dd $e');
      if (e.response?.data != null) {
        final obj = jsonDecode(e.response!.data);
        return obj;
      }
      Future.error(e);
      if (kDebugMode) {
        debugPrint('$baseUrl$url');
      }
    }
    return null;
  }
}
